import React from 'react'
import { connect } from 'react-redux'
import { Mutation } from 'react-apollo'
import {
  Modal, Button, Icon, Header,
} from 'semantic-ui-react'
import { listTable as listTableDuck } from 'ducks'
import Loading from 'components/loading'

const ConfirmModal = ({ modal, actionClose, reFetch }) => {
  const {
    graphqlAction, icon, title, message, submitValues,
  } = modal.config
  if (modal.isOpen === true && graphqlAction !== undefined) {
    return (
      <Mutation mutation={graphqlAction} onCompleted={() => actionClose(reFetch)}>
        {(addTodo, { data, loading, error }) => (
          <Modal basic size="small" open={modal.isOpen}>
            {loading && <Loading color="#FFFFFF" type="bars" width={70} height={70} />}
            {!loading && (
              <React.Fragment>
                <Header icon={icon} content={title} />
                <Modal.Content>
                  {error && <p>{error}</p>}
                  {!error && <p>{message}</p>}
                </Modal.Content>
                <Modal.Actions>
                  <Button
                    basic
                    color="red"
                    inverted
                    onClick={() => actionClose()}
                    disabled={loading}
                  >
                    <Icon name="cancel" />
                    {' '}
取消
                  </Button>
                  <Button
                    color="green"
                    inverted
                    loading={loading}
                    disabled={loading}
                    onClick={() => addTodo({ variables: submitValues })}
                  >
                    <Icon name="checkmark" />
                    {' '}
确定
                  </Button>
                </Modal.Actions>
              </React.Fragment>
            )}
          </Modal>
        )}
      </Mutation>
    )
  }
  return null
}

const mapStateToProps = state => ({
  modal: listTableDuck.selectors.modal(state),
})

const mapDispatchToProps = {
  actionClose: listTableDuck.creators.actionClose,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ConfirmModal)
